package fi.solita.dojo.mazeserver.client

import java.net._
import java.io._

import fi.solita.dojo.mazeserver.game._

class ClientThread(socket: Socket)extends Runnable {
	val out = new OutputStreamWriter(socket.getOutputStream, "ISO-8859-1")
	val in = new BufferedReader(new InputStreamReader(socket.getInputStream, "ISO-8859-1"))

	def run() {	  
		val name = initPlayer()
		try {
			while(true) {
				GameActor ! parse(name, readLine()) 
				Thread.sleep(10)
				if (socket.isClosed) throw new ConnectionTerminatedException
				//receive lines until something goes wrong
			}
		} catch {
		case ex: ConnectionTerminatedException => {}
		} finally (closeConnection(name)) 
	}

	private def closeConnection(name: String) {
		GameActor ! Quit(name)
		ClientService ! Remove(name)
		socket.close      
	}

	private def initPlayer(): String = {
			val name = registerClientName
			ClientService ! Init(name, socket)
			GameActor ! NewPlayer(name)
			name
	}

	private def parse(name: String, line: String) = line match {
	case "quit" => throw new ConnectionTerminatedException()
	case null => throw new ConnectionTerminatedException()
	case s: String => ClientCommand(name, s)
	}

	private def clientName(socket:  Socket) = {
		ClientService.write(out, 
				"Welcome to dojoserver 0.1. Please give your name")
				readLine()
	}

	private def readLine(): String = {
			try {
				in.readLine()
			} catch {
			case ex: SocketException => {
				throw new ConnectionTerminatedException()
			}
			}
	}

	private def registerClientName(): String = {
			var name = clientName(socket)
			while(ClientService.clientNameInUse(name) || name == "") {
				name = clientName(socket)
			}
			name
	}

	private class ConnectionTerminatedException() extends Exception
}
